package com.mingtu.guards.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.center.bean.MyTrackBean;
import com.mingtu.center.bean.MyTrackTotalBean;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.base.BaseFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.room.TrackEvent;
import com.mingtu.common.room.TrackEventDao;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.MyRecordTrackAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.mingtu.guards.utils.MyConstant.animationType;
import static com.mingtu.guards.utils.MyConstant.isFirstOnly;
import static com.mingtu.guards.utils.MyConstant.isOpenLoadAnimation;

public class MyTrackRecordFragment extends BaseFragment implements LazyFragmentPagerAdapter.Laziable {

    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.tv_total_mileage)
    TextView tvTotalMileage;
    @BindView(R.id.tv_total_time)
    TextView tvTotalTime;
    @BindView(R.id.tv_total_count)
    TextView tvTotalCount;

    private int currentPage = 1;
    private boolean isLoadMore = true;
    private MyRecordTrackAdapter myRecordTrackAdapter;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String beginTime = null;
    private String endTime = null;

    public static MyTrackRecordFragment getInstance() {
        MyTrackRecordFragment ef = new MyTrackRecordFragment();
        return ef;
    }

    public static MyTrackRecordFragment getInstance(String beginTime, String endTime) {
        MyTrackRecordFragment ef = new MyTrackRecordFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_PARAM1, beginTime);
        bundle.putString(ARG_PARAM2, endTime);
        ef.setArguments(bundle);
        return ef;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            beginTime = getArguments().getString(ARG_PARAM1);
            endTime = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_track_record;
    }

    @Override
    protected void initData() {
        initListener();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView(View view) {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(manager1);
        recyclerView.addItemDecoration(new TopSpaceItemDecoration());
        recyclerView.addItemDecoration(new BottomSpaceItemDecoration());

        myRecordTrackAdapter = new MyRecordTrackAdapter();
        if (isOpenLoadAnimation) {
            myRecordTrackAdapter.isFirstOnly(isFirstOnly);
            myRecordTrackAdapter.openLoadAnimation(animationType);
        }

        myRecordTrackAdapter.setEmptyView(new EmptyDataLayout(context));
        recyclerView.setAdapter(myRecordTrackAdapter);
        myRecordTrackAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MyTrackBean.PageBean.ListBean listBean = myRecordTrackAdapter.getData().get(position);
                boolean isUpload = listBean.getIsUpload();
                if (isUpload) {
                    String trackId = listBean.getId();
                    Bundle bundle = new Bundle();
                    bundle.putString("trackId", trackId);
                    IntentUtils.getInstance().readyGo(getActivity(), com.mingtu.guards.activity.TrackDetailsActivity.class, bundle);

                } else {
                    ToastUtils.showLong("离线的轨迹数据暂不能查看详情哦");
                }


            }
        });
    }

    @Override
    protected void getData() {
        getMyTrackInfo(1);
        getMyTrackInfoCount();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe
    public void onStringEvent(MyEventBus event) {
        //当用户处在次页面的时候，联网之后刷新数据
        String message = event.getMessgae();
        if (message.equals(Constant.REFRESH_MY_TRACK_DATA)) {
            try {
                getMyTrackInfo(1);
                getMyTrackInfoCount();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }


    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getMyTrackInfo(1);
                getMyTrackInfoCount();
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(myRecordTrackAdapter.getData(), Constant.PAGE_SIZE);
                    getMyTrackInfo(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }


    /**
     * 我的巡护
     */
    private void getMyTrackInfo(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("beginTime", beginTime);
        hashMap.put("endTime", endTime);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(Constant.getInstance().POST_MY_TASK_INFO)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            MyTrackBean myTrackBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                myTrackBean = new MyTrackBean();
                                myTrackBean = gson.fromJson(result, MyTrackBean.class);

                                List<MyTrackBean.PageBean.ListBean> dataBeans = myTrackBean.getPage().getList();

                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (dataBeans != null && dataBeans.size() > 0) {
                                            for (int i = 0; i < dataBeans.size(); i++) {
                                                MyTrackBean.PageBean.ListBean listBean = dataBeans.get(i);
                                                listBean.setIsUpload(true);
                                            }
                                        }

                                        if (currentPage == 1) {
                                            myRecordTrackAdapter.replaceData(dataBeans);
                                        } else {
                                            myRecordTrackAdapter.addData(dataBeans);
                                        }

                                        noUploadData();
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                        noUploadData();
                    }
                });
    }

    /**
     * 我的巡护总信息
     */
    private void getMyTrackInfoCount() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("beginTime", beginTime);
        hashMap.put("endTime", endTime);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(Constant.getInstance().POST_MY_TASK_INFO_COUNT)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            MyTrackTotalBean myTrackTotalBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                myTrackTotalBean = new MyTrackTotalBean();
                                myTrackTotalBean = gson.fromJson(result, MyTrackTotalBean.class);


                                MyTrackTotalBean.CountBean countBean = myTrackTotalBean.getCount();
                                String totalMileage = countBean.getTotalMileage();
                                String totalDuration = countBean.getTotalDuration();
                                String totalCount = countBean.getTotalCount();

                                if (!StringUtils.isEmpty(totalMileage)) {
                                    BigDecimal mileage = new BigDecimal(totalMileage);
                                    double myMileage = mileage.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                                    tvTotalMileage.setText(myMileage + "");
                                }

                                if (!StringUtils.isEmpty(totalCount)) {
                                    tvTotalCount.setText(totalCount + "");
                                }

                                if (!StringUtils.isEmpty(totalDuration)) {
                                    long d = 0;
                                    if (totalDuration.indexOf(".") != -1) {
                                        String array[] = totalDuration.split("\\.");
                                        d = Long.parseLong(array[0]);
                                    } else {
                                        d = Long.parseLong(totalDuration);
                                    }


                                    String timeStr = MyUtills.formatSeconds2(d);
//                                    if (d < 60) {
//                                        tvTotalTime.setText(d + "s");
//                                    } else {
                                    tvTotalTime.setText(timeStr + "");
//                                    }


//                                    String timeStr = MyUtills.formatSeconds(d);
//                                    if (timeStr.indexOf(":") != -1) {
//                                        String timeArray[] = timeStr.split(":");
//                                        String time1 = timeArray[0]; //含有h
//                                        String time2 = timeArray[1]; //含有m
//                                        String time3 = timeArray[2]; //含有s
//
//                                        String timeH = time1.split("h")[0];
//                                        String timeM = time2.split("m")[0];
//                                        String timeS = time3.split("s")[0];
//
//                                        tvTotalH.setText(timeH);
//                                        tvTotalM.setText(timeM);
//                                        tvTotalS.setText(timeS);
//
//                                    }
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }


                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }

    /**
     * 未上传的数据
     */
    private void noUploadData() {
        //未上传的数据
        List<MyTrackBean.PageBean.ListBean> dataBeans = new ArrayList<>();
        TrackEventDao trackEventDao = BaseApplication.getBaseApplication().getTrackEventDao();
        List<TrackEvent> trackEvents = trackEventDao.getAll();
        for (int i = 0; i < trackEvents.size(); i++) {
            MyTrackBean.PageBean.ListBean listBean = new MyTrackBean.PageBean.ListBean();

            TrackEvent trackEvent = trackEvents.get(i);
            String duration = trackEvent.getDuration();
            String beginTime = trackEvent.getBeginTime();
            String endTime = trackEvent.getEndTime();
            String mileage = trackEvent.getMileage();

            listBean.setBeginTime(beginTime);
            listBean.setEndTime(endTime);
            listBean.setDuration(duration);
            listBean.setMileage(mileage);
            listBean.setIsUpload(false);
            dataBeans.add(listBean);
        }
        if (dataBeans.size() > 0) {
            myRecordTrackAdapter.addData(0, dataBeans);
        }
    }

}